package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.enumeration.OperationType;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavourMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavourMapper dishFlavourMapper;

    @Autowired
    private SetMealDishMapper setMealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品和口味
     *
     * @param dishDTO
     */
    @Transactional // 开启事务管理 该方法内的SQL要么全部成功，要么全部失败
    public void saveWithFlavours(DishDTO dishDTO) {
        // 把菜品dish存储到dish表中
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        // 获取返回的主键
        Long dishId = dish.getId();
        // 把口味存储到dish_flavour表中
        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 为dishId赋值
        if (flavors != null && flavors.size() != 0) {
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            // 批量插入口味数据
            dishFlavourMapper.insertFlavours(flavors);
        }
    }

    /**
     * 菜品分页查询
     *
     * @param pageQueryDTO
     * @return
     */
    public PageResult page(DishPageQueryDTO pageQueryDTO) {

        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<DishVO> dishList = dishMapper.page(pageQueryDTO);
        log.info("查询到数据：{}", dishList);
        return new PageResult(dishList.getTotal(), dishList.getResult());
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        // 检查菜品是否处于启售状态
        // 启售状态 不可删除
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                // 当前菜品处于启售状态，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        // 检查菜品是否关联了套餐
        // 关联套餐 不可删除
        List<Long> setMealIds = setMealDishMapper.getSetMealIdsByDishIds(ids);
        if (setMealIds != null && setMealIds.size() > 0) {
            // 当前菜品关联了套餐，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

//        // 删除菜品表中的数据
          // SQL语句数量多，性能不好
//        for (Long id : ids) {
//            dishMapper.deleteById(id);
//            // 删除口味表中对应菜品的口味数据
//            dishFlavourMapper.deleteByDishId(id);
//        }

        // 根据菜品id集合，批量删除菜品数据
        dishMapper.deleteByIds(ids);

        // 根据菜品id集合，批量删除菜品对应的口味数据
        dishFlavourMapper.deleteByDishIds(ids);

    }

    /**
     * 根据ID查询菜品以及对应的口味
     *
     * @param id
     * @return
     */
    public DishVO getByIdWithFlavor(Long id) {
        // 查询dish
        Dish dish = dishMapper.getById(id);
        // 查询口味
        List<DishFlavor> flavors = dishFlavourMapper.getByDishId(id);
        DishVO dishVO = new DishVO();
        // 对象属性拷贝
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        // 准备数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        // 更新菜品
        dishMapper.update(dish);

        // 删除原有的口味数据
        Long dishId = dishDTO.getId();

        dishFlavourMapper.deleteByDishId(dishId);
        // 插入新的口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 为dishId赋值
        if (flavors != null && flavors.size() != 0) {
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            // 批量插入口味数据
            dishFlavourMapper.insertFlavours(flavors);
        }
    }

    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    public void dishStartOrStop(Integer status, Long id) {
        dishMapper.updateStatus(status, id);
        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setMealDishMapper.getSetMealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> getAllByCategoryId(String categoryId) {
        List<Dish> dishList= dishMapper.getBatchByCategoryId(categoryId);
        return dishList;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        // 条件查询菜品数据
        List<Dish> dishList = dishMapper.list(dish);
        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavourMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
